package com.qth.valet.common.rouyi;

import com.qth.valet.common.annotation.RepeatSubmit;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 判断请求url和数据是否和上一次相同，
 * 如果和上次相同，则是重复提交表单。 有效时间为5秒内。
 *
 * @author ruoyi
 */
@Component
public class SameUrlDataInterceptor extends RepeatSubmitInterceptor {
    public final String REPEAT_PARAMS = "repeatParams";

    public final String REPEAT_TIME = "repeatTime";

    public final String SESSION_REPEAT_KEY = "repeatData";

    @SuppressWarnings("unchecked")
    @Override
    public boolean isRepeatSubmit(HttpServletRequest request, RepeatSubmit annotation) throws Exception {
        // 序列化请求参数和当前时间，用于后续比较
        String nowParams = JSON.marshal(request.getParameterMap());
        Map<String, Object> nowDataMap = new HashMap<>();
        nowDataMap.put(REPEAT_PARAMS, nowParams);
        nowDataMap.put(REPEAT_TIME, System.currentTimeMillis());

        // 获取请求的URI作为session中存储的key
        String url = request.getRequestURI();

        // 从session中获取之前存储的重复提交数据
        HttpSession session = request.getSession();
        Object sessionObj = session.getAttribute(SESSION_REPEAT_KEY);

        // 判断session中是否有数据
        if (sessionObj != null) {
            // session不为空
            Map<String, Object> sessionMap = (Map<String, Object>) sessionObj;
            // 判断是否有同一URL
            if (sessionMap.containsKey(url)) {
                // 存在，则判断是否在指定时间内
                Map<String, Object> preDataMap = (Map<String, Object>) sessionMap.get(url);
                // 比较参数和时间间隔，判断是否为重复提交
                if (compareParams(nowDataMap, preDataMap) && compareTime(nowDataMap, preDataMap, annotation.interval())) {
                    return true;
                }
            }
        }
        // 如果不是重复提交，更新session中的数据
        Map<String, Object> sessionMap = new HashMap<>();
        // 存储当前URL和参数
        sessionMap.put(url, nowDataMap);
        // 存储session
        session.setAttribute(SESSION_REPEAT_KEY, sessionMap);
        return false;
    }

    /**
     * 判断参数是否相同
     */
    private boolean compareParams(Map<String, Object> nowMap, Map<String, Object> preMap) {
        String nowParams = (String) nowMap.get(REPEAT_PARAMS);
        String preParams = (String) preMap.get(REPEAT_PARAMS);
        return nowParams.equals(preParams);
    }

    /**
     * 判断两次间隔时间
     */
    private boolean compareTime(Map<String, Object> nowMap, Map<String, Object> preMap, int interval) {
        long time1 = (Long) nowMap.get(REPEAT_TIME);
        long time2 = (Long) preMap.get(REPEAT_TIME);
        return (time1 - time2) < interval;
    }
}
